package com.ioidea.ble.proto

import com.ioidea.base.util.Symbol
import com.ioidea.room.bean.GroupStrategy
import java.text.SimpleDateFormat

/**
 * 3.3 PLC调光策略 PLC_POLICY
数据：组ID当前包 总包 策略条数 (周 时间 亮度1 亮度2 亮度3)
示例：手机->设备
PLC_POLICY_A 1 1 1 2 1 1256 100 100 100 1 1356 80 80 80
示例：设备->手机
PLC_POLICY 1
 */
class ProtoAddStrategy(
    override var requestCommand: String = "PLC_POLICY",
    override var responseCommand: String = "PLC_POLICY"
) : ProtoBase() {

    companion object {
        const val fixSinglePackScheduleNum = 7
    }


    /**
     * @param groupStrategy 策略
     * 一条shcedule 周 时间 亮度1 亮度2 亮度3 1 1256 1000 1000 1000 占21个字节
     * 一包设定最多发送 7条 Schedule
     * @return 数据：组ID当前包 总包 策略条数 (周 时间 亮度1 亮度2 亮度3)
     */
    fun getPayloadList(groupStrategy: GroupStrategy): MutableList<String> {
        val dataList = mutableListOf<String>()
        val groupId = groupStrategy.groupId
        val repeatWeekDayArr = groupStrategy.repeatWeekDays.split(",")
        val scheduleList = groupStrategy.scheduleList.sortedBy { SimpleDateFormat("HH:mm").parse(it.time) }
        // 总共要发送的数据条数
        val totalWithWeekdayScheduleList = mutableListOf<String>()
        repeatWeekDayArr.forEach { weekDay ->
            scheduleList.forEach { strategySchedule ->
                    val eachStr = StringBuilder().append(weekDay).append(Symbol.SPACE)
                        .append(strategySchedule.time.replace(":", "")).append(Symbol.SPACE)
                        .append(strategySchedule.brightness1 * 10).append(Symbol.SPACE)
                        .append(strategySchedule.brightness2 * 10).append(Symbol.SPACE)
                        .append(strategySchedule.brightness3 * 10)
                    totalWithWeekdayScheduleList.add(eachStr.toString())
                }
        }
        val groupList = totalWithWeekdayScheduleList.chunked(fixSinglePackScheduleNum)
        groupList.forEachIndexed { index, stringList: List<String> ->
            val payLoadBuilder = StringBuilder()
            payLoadBuilder.append(groupId).append(Symbol.SPACE).append(index + 1)
                .append(Symbol.SPACE)
                .append(groupList.size).append(Symbol.SPACE).append(stringList.size)
                .append(Symbol.SPACE).append(
                    stringList.joinToString(Symbol.SPACE)
                )
            dataList.add(payLoadBuilder.toString())
        }
        return dataList
    }

}